package com.ltv.xiangqibook.web;

import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class XiangQiPostServlet extends HttpServlet {
	private static final Logger logger = Logger.getLogger(XiangQiPostServlet.class.getCanonicalName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String game_id = req.getParameter("id");
		String author = req.getParameter("author");
		String content = req.getParameter("comment");
		
		if (author == null || author.trim().equals("")
				|| content == null || content.trim().equals("")) {
			resp.sendRedirect("/XiangQiGame");
		} else {
			try {
				Post.createPost(System.nanoTime(), game_id, author, new Text(content), Calendar.getInstance().getTime());
			} catch (Exception e) {
				String errMsg = "Error save Post: " + e.getMessage();
				logger.severe(errMsg);
				throw new ServletException(errMsg);
			}
			
			resp.sendRedirect("/XiangQiGame");
		}
	}

}
